package com.example.petchating.UI

import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.math.Vector2
import ktx.assets.disposeSafely

class ButtonGroup(
    //按钮布局相对于屏幕尺寸
    private val screenWidth : Float,
    private val screenHeight : Float,
    buttonSize: Float = screenWidth / 5f,
    spacing: Float = buttonSize / 6f
) {
    val buttons = mutableListOf<Button>()
    private val buttonAtlas: TextureAtlas = TextureAtlas("UI/button_atlas.atlas") // 加载按钮图集

    init {
        // 初始化四方向按钮（布局：下、左、右、上）
        val buttonRowX = (screenWidth-(buttonSize * 3 + spacing * 2)) / 2 // 水平居中
        val buttonRowY = screenHeight / 6f // 底部1/6高度

        // 下按钮（基础位置）
        val downButton = createButton(
            "button_down", buttonRowX + buttonSize + spacing, buttonRowY-buttonSize, buttonSize
        )
        // 左按钮（左侧）
        val leftButton = createButton(
            "button_left", buttonRowX, buttonRowY, buttonSize
        )
        // 右按钮（右侧）
        val rightButton = createButton(
            "button_right", buttonRowX + buttonSize * 2 + spacing * 2, buttonRowY, buttonSize
        )
        // 上按钮（下按钮正上方）
        val upButton = createButton(
            "button_up", buttonRowX + buttonSize + spacing, buttonRowY + buttonSize + spacing, buttonSize
        )

        buttons.addAll(listOf(upButton, downButton, leftButton, rightButton))
    }

    private fun createButton(
        regionName: String, x: Float, y: Float, size: Float
    ): Button {
        val normalName = regionName+"_normal"
        val pressedName = regionName+"_pressed"
        val normal = buttonAtlas.findRegion(normalName)
        val pressed = buttonAtlas.findRegion(pressedName)
        return Button(normal, pressed, x, y, size, size)
    }


    //该方法遍历 buttons 列表中的所有按钮，并调用每个按钮的 update 方法，根据触摸位置和触摸状态更新按钮的状态
    fun update(inputPos: Vector2, isTouched: Boolean) {
        buttons.forEach { it.update(inputPos, isTouched) }
    }
    //该方法遍历 buttons 列表中的所有按钮，并调用每个按钮的 draw 方法，将按钮绘制到屏幕上。
    fun draw(batch: SpriteBatch) {
        buttons.forEach { it.draw(batch) }
    }

    fun dispose() {
        buttonAtlas.disposeSafely()
    }
}
